const http = require('../../../utils/http.js');
const tools = require('../../../utils/tools.js');

Page({
  data: {
    ck_exam_info: {
      exam_type: '',            // 报考类型 id
      outside_residence: '',    // 区外考生居住地 id
      military_service: '',     // 报考军人服役地 id
      household_location: '',   // 户籍所在地名称（输入框填写）
      candidate_feature: '',    // 考生特征 id
      admission_category: '',   // 招生类别 id
      exam_level: '',           // 报考层次 id
      exam_subject: '',         // 报考科类 id
      study_location: '',       // 报考学习地点 id
      study_mode: '',           // 学习形式 id
      // 报名点信息（分两行显示）
      exam_site_code: '',       // 报名点代码
      exam_site_name: '',       // 报名点名称
      exam_site_address: '',    // 选中的报名点地址
      exam_site_id:'',//选中报名点的id

      postal_code: '',          // 邮政编码
      ck_exam_university_school: '', // 报考志愿院校 id
      ck_major: '',             // 意向专业 id
      emergency_contact: ''     // 紧急联系电话
    },
    showMilitaryService: false,  // 是否显示报考军人服役地
    showOutsideResidence: false, // 是否显示区外考生居住地
    // 下拉选项及下标（均通过后端接口加载）
    examTypeOptions: [],
    examTypeIndex: null,
    outsideResidenceOptions: [],
    outsideResidenceIndex: null,
    militaryServiceOptions: [],
    militaryServiceIndex: null,
    candidateFeatureOptions: [],
    candidateFeatureIndex: null,
    admissionCategoryOptions: [],
    admissionCategoryIndex: null,
    examLevelOptions: [],
    examLevelIndex: null,
    examSubjectOptions: [],
    examSubjectIndex: null,
    studyLocationOptions: [],
    studyLocationIndex: null,
    studyModeOptions: [],
    studyModeIndex: null,
    examSiteOptions: [],
    examSiteIndex: null,
    examSiteAddressOptions: [],
    examSiteAddressIndex: null,
    ckExamUniversitySchoolOptions: [],
    ckExamUniversitySchoolIndex: null,
    ckMajorOptions: [],
    ckMajorIndex: null,
    // 语音相关
    recordedText: null,
    recording: false,
    recordFilePath: '',
    editableContent: '',
    buttonText: '开始录音'
  },

  onLoad() {
      this.loadOptions().then(()=>{
          this.loadStoredInfo;
      }).catch (err=> {
        console.error('加载选项失败:', err);
      })
  },
  async loadOptions(){
      try{
          // 加载各个下拉选项数据，接口地址格式均为 "/chengkao/xxx/all"
          const examTypePromise = tools.fetchOptions('/chengkao/examType/all', 'examTypeOptions', this);
            const outsideResidencePromise = tools.fetchOptions('/chengkao/outsideResidence/all', 'outsideResidenceOptions', this);
            const militaryServicePromise = tools.fetchOptions('/chengkao/militaryService/all', 'militaryServiceOptions', this);
            const candidateFeaturePromise = tools.fetchOptions('/chengkao/candidateFeature/all', 'candidateFeatureOptions', this);
            const admissionCategoryPromise = tools.fetchOptions('/chengkao/admissionCategory/all', 'admissionCategoryOptions', this);
            const examLevelPromise = tools.fetchOptions('/chengkao/examLevel/all', 'examLevelOptions', this);
            const examSubjectPromise = tools.fetchOptions('/chengkao/examSubject/all', 'examSubjectOptions', this);
            const studyLocationPromise = tools.fetchOptions('/chengkao/studyLocation/all', 'studyLocationOptions', this);
            const studyModePromise = tools.fetchOptions('/chengkao/studyMode/all', 'studyModeOptions', this);
            const examSitePromise = tools.fetchOptions1('/chengkao/examSite/all', 'examSiteOptions', this);
            const ckSchoolPromise = tools.fetchOptions('/chengkao/examUniversity/all', 'ckExamUniversitySchoolOptions', this);

            await Promise.all([
                examTypePromise, outsideResidencePromise, militaryServicePromise,
                candidateFeaturePromise, admissionCategoryPromise, examLevelPromise,
                examSubjectPromise, studyLocationPromise, studyModePromise,
                examSitePromise, ckSchoolPromise
              ]);
              this.loadStoredInfo();
      }catch(err){
          console.error('加载选项失败',err)
      }
  },
  async loadStoredInfo(){
    const storedInfo = wx.getStorageSync('ck_exam_info');
    if (storedInfo) {
        this.setData({ ck_exam_info: storedInfo });
        this.updateExamTypeAndInfo(storedInfo)

        await this.loadMajorBySchoolId(storedInfo.ck_exam_university_school)
            // 获取报名点信息对应的code,name,address,并设置
        const item = this.data.examSiteOptions.find(option => option.id === storedInfo.exam_site_id);
        if(item){
            this.setData({
                'ck_exam_info.exam_site_code':item.code,
                'ck_exam_info.exam_site_name':item.name,
                'ck_exam_info.exam_site_address':item.address
              })
        }
        // 加载地址选项
        this.loadExamSiteAddressOptions(item.name);
        this.updateIndex(storedInfo);
      }
  },

  updateIndex(storedInfo) {
    this.setData({
      examTypeIndex: tools.findIndexById(this.data.examTypeOptions, storedInfo.exam_type),
      outsideResidenceIndex: tools.findIndexById(this.data.outsideResidenceOptions, storedInfo.outside_residence),
      militaryServiceIndex: tools.findIndexById(this.data.militaryServiceOptions, storedInfo.military_service),
      candidateFeatureIndex: tools.findIndexById(this.data.candidateFeatureOptions, storedInfo.candidate_feature),
      admissionCategoryIndex: tools.findIndexById(this.data.admissionCategoryOptions, storedInfo.admission_category),
      examLevelIndex: tools.findIndexById(this.data.examLevelOptions, storedInfo.exam_level),
      examSubjectIndex: tools.findIndexById(this.data.examSubjectOptions, storedInfo.exam_subject),
      studyLocationIndex: tools.findIndexById(this.data.studyLocationOptions, storedInfo.study_location),
      studyModeIndex: tools.findIndexById(this.data.studyModeOptions, storedInfo.study_mode),
      examSiteIndex: tools.findIndexById(this.data.examSiteOptions, storedInfo.exam_site_id), // 假设存 exam_site_id 与 examSiteOptions 中 id 对应
      examSiteAddressIndex: tools.findIndexById(this.data.examSiteAddressOptions, storedInfo.exam_site_id),//更新地址的下标
      ckExamUniversitySchoolIndex: tools.findIndexById(this.data.ckExamUniversitySchoolOptions, storedInfo.ck_exam_university_school),
      ckMajorIndex: tools.findIndexById(this.data.ckMajorOptions,storedInfo.ck_major)
    });
  },

  async loadMajorBySchoolId(valueId) {
    // 加载对应院校下的意向专业
   await tools.fetchOptions(`/chengkao/CKMajor/universityId?universityId=${valueId}`, 'ckMajorOptions', this);
  },
  loadExamSiteAddressOptions(examSiteName){
    // 筛选符合条件的 item，并提取 id 和 address
    const addressList = this.data.examSiteOptions.filter(item => item.name === examSiteName)
    .map(item => ({
      id: item.id,
      address: item.address
    }));
    // 设置下拉选项
    this.setData({
      examSiteAddressOptions: addressList,
      examSiteAddressIndex : null //重置地址选项
    })
  },
  updateExamTypeAndInfo(storedInfo){
    // 根据考生类型对报考军人服役地和区外考生居住地信息进行展示
    const name = tools.findNameById(this.data.examTypeOptions, storedInfo.exam_type)
    this.updateExamType(name);
  },
  updateExamType(examTypeName){
    // 根据选中报考类型设置显示条件
    if (examTypeName === '区内户籍报考') {
      this.setData({
        showMilitaryService: false,
        showOutsideResidence: false,
        'ck_exam_info.military_service': '',
        'ck_exam_info.outside_residence': ''
      });
    } else if (examTypeName === '现役军人报考') {
      this.setData({
        showMilitaryService: true,
        showOutsideResidence: false,
        'ck_exam_info.outside_residence': ''
      });
    } else if (examTypeName === '区外户籍工作地报考' || examTypeName === '区外户籍居住地报考') {
      this.setData({
        showMilitaryService: false,
        showOutsideResidence: true,
        'ck_exam_info.military_service': ''
      });
    }
  },

  // 通用输入框回调
  handleInput(e) {
    const { field } = e.currentTarget.dataset;
    this.setData({ [`ck_exam_info.${field}`]: e.detail.value });
  },

  // 下拉选择回调
  handlePickerChange(e) {
    const { field } = e.currentTarget.dataset;
    const index = e.detail.value;
    let valueId = '';
    if (field === 'exam_type') {
      valueId = this.data.examTypeOptions[index].id;
      this.setData({ examTypeIndex: index });
      this.setData({ 'ck_exam_info.exam_type': valueId });
      const examTypeName = this.data.examTypeOptions[index].name;
      // 根据选中报考类型设置显示条件
      this.updateExamType(examTypeName);
    } else if (field === 'outside_residence') {
      valueId = this.data.outsideResidenceOptions[index].id;
      this.setData({ outsideResidenceIndex: index });
      this.setData({ 'ck_exam_info.outside_residence': valueId });
    } else if (field === 'military_service') {
      valueId = this.data.militaryServiceOptions[index].id;
      this.setData({ militaryServiceIndex: index });
      this.setData({ 'ck_exam_info.military_service': valueId });
    } else if (field === 'candidate_feature') {
      valueId = this.data.candidateFeatureOptions[index].id;
      this.setData({ candidateFeatureIndex: index });
      this.setData({ 'ck_exam_info.candidate_feature': valueId });
    } else if (field === 'admission_category') {
      valueId = this.data.admissionCategoryOptions[index].id;
      this.setData({ admissionCategoryIndex: index });
      this.setData({ 'ck_exam_info.admission_category': valueId });
    } else if (field === 'exam_level') {
      valueId = this.data.examLevelOptions[index].id;
      this.setData({ examLevelIndex: index });
      this.setData({ 'ck_exam_info.exam_level': valueId });
    } else if (field === 'exam_subject') {
      valueId = this.data.examSubjectOptions[index].id;
      this.setData({ examSubjectIndex: index });
      this.setData({ 'ck_exam_info.exam_subject': valueId });
    } else if (field === 'study_location') {
      valueId = this.data.studyLocationOptions[index].id;
      this.setData({ studyLocationIndex: index });
      this.setData({ 'ck_exam_info.study_location': valueId });
    } else if (field === 'study_mode') {
      valueId = this.data.studyModeOptions[index].id;
      this.setData({ studyModeIndex: index });
      this.setData({ 'ck_exam_info.study_mode': valueId });
    } if (field === 'exam_site') {
      // 选择报名点（第一行）：显示 code 和 name，通过 display 字段直接展示
      const selected = this.data.examSiteOptions[index];
      this.setData({
        examSiteIndex: index,
        'ck_exam_info.exam_site_code': selected.code,
        'ck_exam_info.exam_site_name': selected.name
      });
      // 根据选中报名点的 code，从 examSiteOptions 中筛选出所有地址（假设可能有多个地址）
      this.loadExamSiteAddressOptions(selected.name);
      return;
    } else if (field === 'exam_site_address') {
      // 选择报名点地址（第二行）
      const selected = this.data.examSiteAddressOptions[index];
      this.setData({
        examSiteAddressIndex: index,
        'ck_exam_info.exam_site_address': selected.address,
        'ck_exam_info.exam_site_id':selected.id
      });
      return;
    } else if (field === 'ck_exam_university_school') {
      valueId = this.data.ckExamUniversitySchoolOptions[index].id;
      this.setData({ ckExamUniversitySchoolIndex: index });
      this.setData({ 'ck_exam_info.ck_exam_university_school': valueId });
      // 加载对应院校下的意向专业
      this.loadMajorBySchoolId(valueId)
      return;
    } else if (field === 'ck_major') {
      valueId = this.data.ckMajorOptions[index].id;
      this.setData({ ckMajorIndex: index });
      this.setData({ 'ck_exam_info.ck_major': valueId });
    } else if (field === 'postal_code' || field === 'household_location' || field === 'emergency_contact') {
      return;
    }
    this.setData({ [`ck_exam_info.${field}`]: valueId });
  },

  handleInput(e) {
    const { field } = e.currentTarget.dataset;
    this.setData({ [`ck_exam_info.${field}`]: e.detail.value });
  },

  handleSubmit() {
    // 检查字段是否更改
    const fieldsToCheck = [
      'exam_type',                 // 报考类型
      'outside_residence',         // 区外考生居住地
      'military_service',          // 报考军人服役地
      'household_location',        // 户籍所在地
      'candidate_feature',         // 考生特征
      'admission_category',        // 招生类别
      'exam_level',                // 报考层次
      'exam_subject',              // 报考科类
      'study_location',            // 报考学习地点
      'study_mode',                // 学习形式
      'exam_site_id',              // 报名点 ID
      'postal_code',               // 邮政编码
      'ck_exam_university_school', // 报考志愿院校（前端字段）
      'ck_major',                  // 意向专业（前端字段）
      'emergency_contact'          // 紧急联系电话
    ];
    if(tools.checkDataChanged(this.data.ck_exam_info,wx.getStorageSync('ck_exam_info'),fieldsToCheck)){
      const idNumber = wx.getStorageSync('base_candidate_info').id_number;
      const postData = {
        idNumber : idNumber,
        examTypeId: this.data.ck_exam_info.exam_type, // 注意：handlePickerChange 中需更新 ck_exam_info.exam_type 为后端期望值
        outsideResidenceId: this.data.ck_exam_info.outside_residence,
        militaryServiceId: this.data.ck_exam_info.military_service,
        householdLocation: this.data.ck_exam_info.household_location,
        candidateFeatureId: this.data.ck_exam_info.candidate_feature,
        admissionCategoryId: this.data.ck_exam_info.admission_category,
        examLevelId: this.data.ck_exam_info.exam_level,
        examSubjectId: this.data.ck_exam_info.exam_subject,
        studyLocationId: this.data.ck_exam_info.study_location,
        studyModeId: this.data.ck_exam_info.study_mode,
        examSiteId: this.data.ck_exam_info.exam_site_id, // 根据实际情况调整，这里可保存报名点的 id
        postalCode: this.data.ck_exam_info.postal_code,
        examUniversityId: this.data.ck_exam_info.ck_exam_university_school, // 前端字段 ck_exam_university_school 对应 examUniversityId
        majorId: this.data.ck_exam_info.ck_major,           // 前端字段 ck_major 对应 majorId
        emergencyContact: this.data.ck_exam_info.emergency_contact
      };
      http.post("/chengkao/CKregistration/upsert", postData)
      .then(res => {
        if (res.data.code === 200) {
          wx.setStorageSync('ck_exam_info', this.data.ck_exam_info);
          wx.showToast({ title: '报考信息更新成功', duration: 2000 });
          wx.reLaunch({
            url: '/pages/chengkao/ck_exam_registrationInfo/ck_exam_registrationInfo',
          })
        }
      })
      .catch(err => {
        console.error('报考信息更新失败:', err);
        wx.showToast({ title: '报考信息更新失败', icon: 'none', duration: 2000 });
      });
    }else{
      wx.reLaunch({
        url: '/pages/chengkao/ck_exam_registrationInfo/ck_exam_registrationInfo',
      })
    }
  },

  // 语音录制、上传及识别功能，与前面页面类似
  // 录音功能区
  toggleRecording() {
    if (this.data.recording) {
      this.setData({ recording: false });
      const recorderManager = wx.getRecorderManager();
      recorderManager.stop();
      recorderManager.onStop((res) => {
        wx.setStorageSync('recordPath', res.tempFilePath);
        this.setData({ recordFilePath: res.tempFilePath });
        this.setData({ buttonText: '开始录音' });
      });
    } else {
      tools.checkRecordPermission().then(() => {
        this.setData({ recording: true });
        const recorderManager = wx.getRecorderManager();
        recorderManager.start({
          format: 'wav',
          duration: 60000,
          sampleRate: 44100,
          numberOfChannels: 1,
          encodeBitRate: 96000
        });
        this.setData({ buttonText: '停止录音' });
      }).catch(() => {
        wx.showToast({ title: '录音权限未授权', icon: 'none' });
      });
    }
  },    
    
  uploadAndRecognizeRecording() {
    if (!this.data.recordFilePath) {
      wx.showToast({ title: '请先录制录音', icon: 'none' });
      return;
    }
    const filePath = this.data.recordFilePath;
    http.asr(filePath).then(res =>{
      console.log("语音识别成功，文本如下：")
      console.log(res);
      // 根据返回的文本信息，提取其中的信息
      this.setData({ editableContent: res });
      // 调用后端的提取接口
      const postData = { "text": res };
      http.ckExtract(postData).then(res =>{
        // 处理提取后的结果
        console.log("提取后的结果，如下：")
        console.log(res)
        this.updateIdAndIndex(res.data)
      }).catch(err => {
        // 提取失败
        console.log('无法解析识别结果：', err);
        console.log('接收到的原始返回数据：', err.data);
      });
    }).catch(err =>{
      // 语音识别失败
      console.log('语音识别失败：', err);
      wx.showToast({ title: '录音识别失败', icon: 'none', duration: 2000 });
    })
  },
    
  updateIdAndIndex(dataFields){
    // 直接赋值的字段（无需匹配 ID 的）
    const fields = ["household_location", "postal_code", "emergency_contact"];
    // 需要匹配 id 和 index 的字段
    // name -> id 映射关系
    const idFields = {
      exam_type: 'exam_type',
      outside_residence: 'outside_residence',
      military_service: 'military_service',
      candidate_feature: 'candidate_feature',
      admission_category: 'admission_category',
      exam_level: 'exam_level',
      exam_subject: 'exam_subject',
      study_location: 'study_location',
      study_mode: 'study_mode',
      // 选中的报名点部分进行特殊处理
      // exam_site_name: 'exam_site_id',  
      // ck_exam_university_school
      ck_exam_university_school: 'ck_exam_university_school',
      // 对专业进行特殊处理
      // ck_major: 'ck_major'
    };

    // name -> 选项数组的映射关系
    const arrayFields = {
        exam_type: 'examTypeOptions',
        outside_residence: 'outsideResidenceOptions',
        military_service: 'militaryServiceOptions',
        candidate_feature: 'candidateFeatureOptions',
        admission_category: 'admissionCategoryOptions',
        exam_level: 'examLevelOptions',
        exam_subject: 'examSubjectOptions',
        study_location: 'studyLocationOptions',
        study_mode: 'studyModeOptions',
        // 报名点选项进行特殊处理
        // exam_site_name: 'examSiteOptions', 
        // 选择报名点的代码后更新
        // exam_site_address: 'examSiteAddressOptions',
        // ck_exam_university_school
        ck_exam_university_school: 'ckExamUniversitySchoolOptions',
        // 对专业进行特殊处理
        // ck_major: 'majorOptions'
    };

    // 根据结果给字段赋值
    fields.forEach(key =>{
      if(!dataFields[key].includes("未知")){
          this.setData({
              [`ck_exam_info.${key}`]:dataFields[key]
          })
      }
    })

    // 根据名字赋值id
    Object.entries(idFields).forEach(([key,value]) =>{
      // 通过两个字典的映射获取对应的值，查询id随后进行赋值
      if(!dataFields[key].includes("未知")){
          this.setData({
              [`ck_exam_info.${value}`]:tools.findIdByName(this.data[arrayFields[key]],dataFields[key])
          })
      }
    })

    // 检查报考类型信息的条件
    this.updateExamTypeAndInfo(this.data.ck_exam_info);
    // 对学校和专业信息进行处理
    // 根据学校的id 查询包含的专业信息
    this.loadMajorBySchoolId(this.data.ck_exam_info.ck_exam_university_school);
    // 根据专业名称查询专业id
    if(!dataFields['ck_major'].includes("未知")){
      this.setData({
        'ck_exam_info.ck_major' : tools.findIdByName(this.data.ckMajorOptions,dataFields['ck_major'])
      })
    }          

    // 对报名点信息进行更新
    // id?未保存
    if(!dataFields['exam_site_address'].includes("未知")){
      // 获取报名点信息对应的code,name,address,并设置
      const item = this.data.examSiteOptions.find(option => option.address === dataFields['exam_site_address']);
      this.setData({
        ['ck_exam_info.exam_site_id']:item.id,
        ['ck_exam_info.exam_site_code']:item.code,
        ['ck_exam_info.exam_site_name']:item.name,
        ['ck_exam_info.exam_site_address']:item.address
      })
      // 加载地址选项
      this.loadExamSiteAddressOptions(item.name);
    }else if(!dataFields['exam_site_name'].includes("未知")){
      // 获取报名点信息对应的code,name,address,并设置
      const item = this.data.examSiteOptions.find(option => option.name === dataFields['exam_site_name']);
      this.setData({
        ['ck_exam_info.exam_site_id']:item.id,
        ['ck_exam_info.exam_site_code']:item.code,
        ['ck_exam_info.exam_site_name']:item.name,
        ['ck_exam_info.exam_site_address']:item.address
      })
      // 加载地址选项
      this.loadExamSiteAddressOptions(item.name);
    }

    //更新下标
    this.updateIndex(this.data.ck_exam_info)
  },
});
